/**
 * 书籍推荐接口
 */
import shuffle from 'lodash/shuffle';
import { Book } from '../models';

export default function (router) {
  /**
   * 前端接口
   * 推荐书籍接口
   * 推荐这本书相关的其他书籍
   */
  router.post('/api/front/recommend', async ctx => {
    const { key = 'default', extra = {} } = ctx.request.body;
    const sortOption = {};
    const findOption = {};
    let books = [];
    if (key === 'book') {
      if (extra.bookid) {
        const thisBook = await Book.findById(extra.bookid);
        if (thisBook) {
          findOption.$or = [{ autor: thisBook.author }, { classify: thisBook.classify }];
          findOption._id = { $ne: thisBook._id };
        }
      }
      sortOption.hot_value = -1;
      sortOption.create_time = -1;
      const randomBooks = await Book.find(findOption, 'name author img_url des').sort(sortOption).limit(3);
      const randomBookIds = randomBooks.map(item => item._id);
      const hotValueBooks = await Book.find({ _id: { $nin: randomBookIds } }, 'name author img_url des')
        .sort({ create_time: -1, hot_value: -1 })
        .limit(randomBooks ? 6 - randomBooks.length : 6);
      books = [...shuffle(hotValueBooks), ...shuffle(randomBooks)];
    } else if (key === 'default') {
      sortOption.hot_value = -1;
      sortOption.create_time = -1;
      books = await Book.find(findOption, 'name author img_url des').sort(sortOption).limit(6);
    }
    await ctx.json('ok', 'success', books);
  });
}
